package org.spring.utils.common;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String uri = request.getRequestURI();//获取请求的地址
        if(uri.contains("auth")){//如果包含则放行--即登录或者是注册
            filterChain.doFilter(request,response);
            return;//放行
        }
        //如果不是登录则进行拦截并获取请求的token
        String token = request.getHeader("token");
        if(JWTUtils.valid(token)){//校验token
            String username = JWTUtils.getUsername(token);//从token解析出登录的用户名

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, "", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);//把登录信息存入上下文中
            filterChain.doFilter(request,response);
            return;
        }
        filterChain.doFilter(request,response);//token有问题的,继续走后续的过滤器
    }
}
